package com.antu.first.web.merchant;

import com.alibaba.fastjson.JSON;
import com.antu.first.bean.Hotel;
import com.antu.first.bean.Indent;
import com.antu.first.bean.Merchant;
import com.antu.first.dto.IndentOperationExecution;
import com.antu.first.dto.MerchantOperationExecution;
import com.antu.first.exceptions.IndentOperationException;
import com.antu.first.service.IndentService;
import com.antu.first.service.MerchantLogionService;
//import com.google.gson.Gson;
import com.antu.first.service.MerchantService;
import com.antu.first.util.PhoneCode;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/merchantController",produces = "text/plain;charset=utf-8")
public class MerchantController {
    @Autowired
    private MerchantLogionService merchantLogionService;
    @Autowired
    private IndentService indentService;
    @Autowired
    private MerchantService merchantService;
    Map<String, Object> modelMap=new HashMap<String, Object>();

   //商家登录
    @RequestMapping(value = "/merchantLogin")
    @ResponseBody
    public String merchantLogin(Merchant merchant,HttpServletRequest request){
        try {
            modelMap =merchantLogionService.merchantlogin(merchant,request) ;
        } catch (Exception e) {
            modelMap.put("errMsg","商家登录错误，请稍后再试");
            e.printStackTrace();
        }
        String str=JSON.toJSONString(modelMap);
        return str;
    }
    //获取手机号，产生验证码
    @RequestMapping(value = "/merchantGetPhoneCode",method = RequestMethod.POST)
    @ResponseBody
    public String merchantGetPhoneCode(String mPhone,HttpServletRequest request){
        request.getSession().setAttribute("merchantPhone",mPhone);
        try {
            modelMap=merchantLogionService.validateMerchantPhone(mPhone,request);
        } catch (Exception e) {
            modelMap.put("errMsg","产生手机验证码错误，请稍后再试");
            e.printStackTrace();
        }
        String str=JSON.toJSONString(modelMap);
        return str;
    }
    //忘记密码，修改密码
    @RequestMapping(value = "/merchantForgetPassword",method = RequestMethod.POST)
    @ResponseBody
    public String merchantForgetPassword(String mNewPassword,String mCode,HttpServletRequest request){
        try {
            modelMap=merchantLogionService.merchantForgetPassword(mNewPassword,mCode,request);
        } catch (Exception e) {
            modelMap.put("errMsg","修改密码错误，请稍后再试");
            e.printStackTrace();
        }
        String str=JSON.toJSONString(modelMap);
        return str;
    }

    @RequestMapping(value = "/getindentlist", method = RequestMethod.GET)
    @ResponseBody
    public String getIndentList(String start, String end, String sequence, String name, int status, int pageIndex){
        //需要前端传入订单状态（必需，状态值：0未使用，1使用中，2已完成，3退款中,4已退款）以及页码
        //除此之外，前端可以选择性的传入订单创建的时间区间、使用人、订单号等参数
        Map<String, Object> modelMap=new HashMap<String, Object>();
        try {
            Date startDate=null;
            Date endDate=null;
            SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
            if(start != null && !"".equals(start)){
                startDate = formatter.parse(start);
            }
            if(end != null && !"".equals(end)){
                endDate = formatter.parse(end);
            }
            //TODO 从Session中获取酒店Id
            Indent indent=new Indent();
            indent.setiUserName(name);
            indent.setiSequence(sequence);
            indent.setiStatus(status);
            Hotel hotel = new Hotel();
            hotel.sethId(3);
            indent.setHotel(hotel);
            if("".equals(indent.getiSequence())){
                indent.setiSequence(null);
            }
            if("".equals(indent.getiUserName())){
                indent.setiUserName(null);
            }
            IndentOperationExecution execution=execution=indentService.queryIndentList(startDate,endDate,indent,pageIndex);
            if(execution.getState()!=1){
                modelMap.put("success",false);
                modelMap.put("errMsg",execution.getStateInfo());
                return JSON.toJSONString(modelMap);
            }
            modelMap.put("success", true);
            modelMap.put("indents", execution.getIndents());
            modelMap.put("recordsNum", execution.getCount());
            modelMap.put("pageNum", (execution.getCount()/10)+1);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "在获取订单列表的过程中发生错误，错误信息："+e.getMessage());
            throw new IndentOperationException("获取订单的过程中发生错误，错误信息："+e.toString());
        }
        return JSON.toJSONString(modelMap);
    }
    @RequestMapping(value = "/checkinhotel",method = RequestMethod.GET)
    @ResponseBody
    public String checkInHotel(int iId, String iSequence, String checkCode){
        Map<String, Object> modelMap = new HashMap<String, Object>();
        try {
            IndentOperationExecution execution = indentService.checkInHotel(iId, iSequence, checkCode);
            if(execution.getState() != 1){
                modelMap.put("success",false);
                modelMap.put("errMsg","确认入住失败，请确保您处于登录状态！");
                return JSON.toJSONString(modelMap);
            }
            modelMap.put("success", true);
            modelMap.put("msg","入住信息已确认！");
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "确认入住的过程中发生错误，错误信息："+e.getMessage());
            throw  new IndentOperationException("确认入住的过程中发生错误，错误信息："+e.getMessage());
        }
        return JSON.toJSONString(modelMap);
    }

    @RequestMapping(value = "/checkouthotel", method = RequestMethod.GET)
    @ResponseBody
    public String checkOutHotel(int iId, String iSequence){
        //确认用户退房请求，需要从前端传入对应的
        Map<String, Object> modelMap = new HashMap<String, Object>();
        try {
            IndentOperationExecution execution = indentService.checkOutHotel(iId, iSequence);
            if(execution.getState() != 1){
                modelMap.put("success", false);
                modelMap.put("errMsg", execution.getStateInfo());
                return JSON.toJSONString(modelMap);
            }
            modelMap.put("success", false);
            modelMap.put("msg", "退房信息已确认");
        } catch(Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "操作情况异常，请联系平台管理员！");
        }
        return JSON.toJSONString(modelMap);
    }

    @RequestMapping(value = "addmerchant", method = RequestMethod.POST)
    @ResponseBody
    public String addMerchant(Merchant merchant){
        Map<String, Object> modelMap = new HashMap<String, Object>();
        //向Root管理员所属的酒店插入对应的子管理员
        //需要插入的字段包括：mUsername,mPassword,mPhone
        try{
            //TODO 从Session中获取当前的Merchant对象
            Hotel hotel = new Hotel();
            hotel.sethId(3);
            Merchant currentMerchant = new Merchant();
            currentMerchant.setmId(6);
            currentMerchant.setHotel(hotel);
            currentMerchant.setmType(0);

            merchant.setmCreateTime(new Date());
            merchant.setmLastEditTime(new Date());
            merchant.setHotel(currentMerchant.getHotel());
            merchant.setOnline(false);
            merchant.setmType(1);
            MerchantOperationExecution execution = merchantService.addMerchant(currentMerchant, merchant);
            if(execution.getState() != 0){
                modelMap.put("success", false);
                modelMap.put("errMsg", execution.getStateInfo());
                return JSON.toJSONString(modelMap);
            }
            modelMap.put("success", true);
            modelMap.put("msg", execution.getStateInfo());
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "服务器异常，请稍后重试！");
        }
        return JSON.toJSONString(modelMap);
    }

    /**
     *修改管理员的信息，能够修改的字段包括管理员密码、管理员联系方式
     * 该实体中需要装入以下信息，管理员密码，管理员联系方式，管理员id(非必须)
     */
    @RequestMapping(value = "modfifymerchantinfo", method = RequestMethod.POST)
    @ResponseBody
    public String modifyMerchantInfo(Merchant merchant){
        Map<String, Object> modelMap = new HashMap<String, Object>();
        try {
            //TODO 从Session中获取Merchant实体信息
            Merchant currentMerchant = new Merchant();
            currentMerchant.setmId(6);
            //如果前端传入的mid和当前Merchant的mid不相同，说明是修改其子管理员的账号信息
            if(merchant.getmId() == 0){
                merchant.setmId(currentMerchant.getmId());
            }
            MerchantOperationExecution execution = merchantService.modifyMerchant(merchant);
            if(execution.getState() != 0){
                modelMap.put("success", false);
                modelMap.put("errMsg", "更新用户信息失败，请联系平台管理员！");
                return JSON.toJSONString(modelMap);
            }
            modelMap.put("success", true);
            modelMap.put("msg", "修改用户信息成功！");
        } catch (Exception e){
            modelMap.put("success", false);
            modelMap.put("errMsg", "服务器异常，请稍后重试！");
        }
        return JSON.toJSONString(modelMap);
    }

    @RequestMapping(value = "/deletemerchant", method = RequestMethod.GET)
    @ResponseBody
    public String deleteMerchant(int mId){
        Map<String, Object> modelMap = new HashMap<String, Object>();
        try {
            //TODO 从Session中获取Merchant实体信息
            Merchant merchant = new Merchant();
            merchant.setmId(6);

            MerchantOperationExecution execution = merchantService.deleteMerchant(merchant, mId);
            if(execution.getState() != 0){
                modelMap.put("success", false);
                modelMap.put("errMsg", execution.getStateInfo());
                return JSON.toJSONString(modelMap);
            }
            modelMap.put("success", true);
            modelMap.put("errMsg", execution.getStateInfo());
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "服务器异常，请稍后重试！");
        }
        return JSON.toJSONString(modelMap);
    }

    @RequestMapping(value = "queryMerchant", method = RequestMethod.GET)
    @ResponseBody
    public String queryMerchantById(int mId){
        Map<String, Object> modelMap = new HashMap<String, Object>();
        try{
            Merchant merchant = merchantService.queryMerchantById(mId);
            if(merchant == null){
                modelMap.put("success", false);
                modelMap.put("errMsg", "查询信息失败！");
                return JSON.toJSONString(modelMap);
            }
            modelMap.put("success", true);
            modelMap.put("merchant", merchant);
        }catch(Exception e){
            modelMap.put("success", false);
            modelMap.put("errMsg", "服务器异常，请稍后重试！");
        }
        return JSON.toJSONString(modelMap);
    }

    @RequestMapping(value = "/querymerchantlist", method = RequestMethod.GET)
    @ResponseBody
    public String queryMerchantList(){
        Map<String, Object> modelMap = new HashMap<String, Object>();
        try {
            //TODO 从Session中获取对应的currentMerchant对象
            Hotel hotel = new Hotel();
            hotel.sethId(3);
            Merchant currentMerchant = new Merchant();
            currentMerchant.setHotel(hotel);

            MerchantOperationExecution execution = merchantService.queryAlls(currentMerchant.getHotel().gethId());
            if(execution.getState() != 0 || execution.getCount() ==0){
                modelMap.put("success", false);
                modelMap.put("errMsg", execution.getStateInfo());
                return JSON.toJSONString(modelMap);
            }
            modelMap.put("success", true);
            modelMap.put("merchants", execution.getMerchants());
            modelMap.put("recordsNum", execution.getCount());
            modelMap.put("pageNum", (execution.getCount()/10)+1);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "服务器异常，请稍后重试！");
        }
        return JSON.toJSONString(modelMap);
    }

    //商家退出后修改在线状态
    @RequestMapping(value = "/updateMerchantIsOnlineAfterExit",method = RequestMethod.POST)
    @ResponseBody
    public String updateMerchantIsOnlineAfterExit(HttpServletRequest request){
        System.out.println("ctr");
        Merchant merchant=(Merchant) request.getSession().getAttribute("merchant");
        try {
            modelMap=merchantLogionService.updateMerchantIsOnlineAfterExit(merchant);
        } catch (Exception e) {
            modelMap.put("errMsg","商家退出后修改在线状态码错误，请稍后再试");
            e.printStackTrace();
        }
        return JSON.toJSONString(modelMap);
    }
}
